package com.bp.hearthealth.pulse.lnapps.bp_ui.bp_activity.bp_language_gender.bp_language

import android.content.Intent
import android.os.Process
import android.view.View
import androidx.lifecycle.Observer
import com.anythink.core.api.ATAdInfo
import com.anythink.core.api.AdError
import com.anythink.nativead.api.ATNativeAdView
import com.anythink.nativead.api.ATNativePrepareExInfo
import com.anythink.nativead.api.ATNativePrepareInfo
import com.bp.hearthealth.pulse.lnapps.BpApplication
import com.bp.hearthealth.pulse.lnapps.ads.admob.interstitial_ad.AdMobInterstitialAdListener
import com.bp.hearthealth.pulse.lnapps.ads.admob.interstitial_ad.AdMobInterstitialAdManager
import com.bp.hearthealth.pulse.lnapps.ads.admob.native_ad.AdMobNativeAdListener
import com.bp.hearthealth.pulse.lnapps.ads.admob.native_ad.AdMobNativeAdManager
import com.bp.hearthealth.pulse.lnapps.ads.admob.rewarded_ad.AdMobRewardedAdManager
import com.bp.hearthealth.pulse.lnapps.ads.model.AdsSwitch
import com.bp.hearthealth.pulse.lnapps.ads.topon.interstitial_ad.TopOnInterAdManager
import com.bp.hearthealth.pulse.lnapps.ads.topon.interstitial_ad.listener.manual_load.TopOnInterstitialAdListener
import com.bp.hearthealth.pulse.lnapps.ads.topon.native_ad.SelfRenderViewUtil
import com.bp.hearthealth.pulse.lnapps.ads.topon.native_ad.TopOnNativeAdListener
import com.bp.hearthealth.pulse.lnapps.ads.topon.native_ad.TopOnNativeAdManager
import com.bp.hearthealth.pulse.lnapps.appsflyer.AppsFlyerUtils
import com.bp.hearthealth.pulse.lnapps.base.BpBaseActivity
import com.bp.hearthealth.pulse.lnapps.bp_extension.LogUtil
import com.bp.hearthealth.pulse.lnapps.bp_ui.bp_activity.bp_language_gender.bp_gender.BpGenderActivity
import com.bp.hearthealth.pulse.lnapps.bp_ui.bp_activity.bp_language_gender.bp_splash.BpSplashActivity
import com.bp.hearthealth.pulse.lnapps.bp_ui.bp_activity.bp_main.BpMainActivity
import com.bp.hearthealth.pulse.lnapps.bp_ui.bp_adapter.BpLanguageTypeAdapter
import com.bp.hearthealth.pulse.lnapps.bp_ui.bp_bean.LanguageItemBean
import com.bp.hearthealth.pulse.lnapps.bp_utils.Constants
import com.bp.hearthealth.pulse.lnapps.bp_utils.DoubleClickListener
import com.bp.hearthealth.pulse.lnapps.bp_utils.MultiLanguageUtils.changeAppLanguage
import com.bp.hearthealth.pulse.lnapps.bp_utils.SpUtils
import com.bp.hearthealth.pulse.lnapps.databinding.ActivityLanguageBgBinding
import com.google.android.gms.ads.nativead.NativeAd
import com.gyf.immersionbar.ImmersionBar
import com.hjq.toast.Toaster
import org.koin.androidx.viewmodel.ext.android.viewModel
import java.util.Locale


class BpLanguageActivity : BpBaseActivity<ActivityLanguageBgBinding>() {

    private var nativeAd: NativeAd? = null
    private var languageFrom: String? = null //null：首次打开，!=null：MeFragment打开
    private var firstOpen: Boolean = true
    private var languageId: Int = 0
    private val languageTypeAdapter = BpLanguageTypeAdapter()
    private val viewMode: BpLanguageViewModel by viewModel()
    private val languageList: MutableList<LanguageItemBean> = ArrayList()
    private var topOnNativeAd: com.anythink.nativead.api.NativeAd? = null

    override fun initData() {
        super.initData()
        //语言选择页-页面展示
        AppsFlyerUtils.trackEvent("language_show")
        registerObserver()
        languageFrom = intent.getStringExtra(Constants.LANGUAGE_FORM)
        viewMode.userBean(Constants.USER_ID)
//        loadNativeAd()
        loadTopOnNativeAd()
    }


    override fun onPause() {
        if (topOnNativeAd != null) {
            topOnNativeAd!!.onPause()
        }
        super.onPause()
    }

    override fun onResume() {
        if (topOnNativeAd != null) {
            topOnNativeAd!!.onResume()
        }
        super.onResume()
    }



    private fun loadTopOnNativeAd() {
        if (TopOnNativeAdManager.getNativeAds().isNotEmpty()) {
            setNativeTopOnAdView()
        } else {
            TopOnNativeAdManager.setNativeAdListener(object : TopOnNativeAdListener{
                override fun onNativeAdLoaded() {
                    LogUtil.iTopOn("TopOn 【原生广告】 监听，显示广告")
                    if (TopOnNativeAdManager.getNativeAds().isNotEmpty()) {
                        setNativeTopOnAdView()
                    }
                }
            })
        }
    }

    private fun setNativeTopOnAdView() {
        topOnNativeAd = TopOnNativeAdManager.getNativeAds().first()
        TopOnNativeAdManager.setNativeAdListener(object : TopOnNativeAdListener {
            override fun onAdImpressed(view: ATNativeAdView, entity: ATAdInfo) {
                TopOnNativeAdManager.removeUsedNativeAdListener()
            }

            override fun onFireBaseAdIsClosed() {
                TopOnNativeAdManager.removeUsedNativeAdListener()
            }
        })
        binding.nativeAdView.removeAllViews()
        var mNativePrepareInfo: ATNativePrepareInfo? = null
        try {
            mNativePrepareInfo = ATNativePrepareExInfo()
            if (topOnNativeAd?.isNativeExpress == true) {
                LogUtil.iTopOn("【原生广告】 自渲染广告")
                topOnNativeAd?.renderAdContainer(
                    binding.nativeAdView,
                    null
                )
            } else {
                LogUtil.iTopOn("【原生广告】 模板广告")
                SelfRenderViewUtil.bindSelfRenderView(
                    activity,
                    topOnNativeAd?.adMaterial,
                    binding.nativeSelfrenderView.root,
                    mNativePrepareInfo
                )
                topOnNativeAd?.renderAdContainer(
                    binding.nativeAdView,
                    binding.nativeSelfrenderView.root
                )
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        topOnNativeAd?.prepare(binding.nativeAdView, mNativePrepareInfo)
        binding.nativeAdView.visibility = View.VISIBLE
        TopOnNativeAdManager.setNativeAdListener(object : TopOnNativeAdListener {
            override fun onAdCloseButtonClick(view: ATNativeAdView, entity: ATAdInfo) {
                TopOnNativeAdManager.destroyAd()
                binding.nativeAdView.visibility = View.GONE
            }
        })
    }


    /**
     * 加载原生广告
     *     ■ 原生广告资源加载到，展示广告
     *     ■ 原生广告资源未加载到，隐藏广告位
     */
    private fun loadNativeAd() {
        AdMobNativeAdManager.setNativeAdListener(object : AdMobNativeAdListener {
            override fun onAdLoaded(loadedNativeAd: MutableList<NativeAd>) {
                setNativeAdView(loadedNativeAd)
            }

            override fun onAdImpression() {
                //原生广告埋点
                AppsFlyerUtils.trackEvent("ad_native_language_show")
                AdMobNativeAdManager.removeUsedNativeAdListener()
            }
        })
        val nativeAdList = AdMobNativeAdManager.getNativeAds()
        if (nativeAdList.isNotEmpty()) {
            setNativeAdView(nativeAdList)
        }
    }

    private fun setNativeAdView(nativeAdList: MutableList<NativeAd>) {
        nativeAd = nativeAdList.first()
        binding.nativeAdContainer.setNativeAd(nativeAd)
        binding.nativeAdContainer.visibility = View.VISIBLE
    }

    private fun registerObserver() {
        viewMode.userBeanAndLanguage.observe(this, Observer {
            val response = it.userResult.getOrNull()
            if (response == null) {
                Toaster.show(it.userResult.exceptionOrNull())
                LogUtil.e(it.userResult.exceptionOrNull().toString())
                return@Observer
            }
            firstOpen = response.isFirstOpen
            if (response.languageList.size != it.languageCodes.size) {
                LogUtil.e("response.languageList.size != it.languageCodes.size !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
                startActivity(Intent(activity, BpMainActivity::class.java))
                finish()
            } else {
                for (index in response.languageList.indices) {
                    languageList.add(
                        LanguageItemBean(
                            response.languageList[index],
                            it.languageCodes[index].language,
                            it.languageCodes[index].code
                        )
                    )
                }
                languageTypeAdapter.setData(languageList)
                binding.recyclerView.adapter = languageTypeAdapter
            }
        })
        viewMode.updateLanguage.observe(this, Observer {
            val response = it.getOrNull()
            if (response == null) {
                Toaster.show(it.exceptionOrNull())
                LogUtil.e(it.exceptionOrNull().toString())
//                return@Observer
            }
            SpUtils.saveString(Constants.IS_SET_LANGUAGE, Constants.IS_SET_LANGUAGE)
//            loadAdMobInsertAd()
            loadTopOnInsertAd()
            //未加广告前逻辑
//            if (languageList[languageId].language == Constants.dfT && languageList[languageId].area == Constants.dfC && languageFrom.isNullOrEmpty()) {
//                startActivity(Intent(BpApplication.context, BpGenderActivity::class.java))
//                finish()
//            } else {
//                releaseAdInfo()
//                killProcess()
//            }

//            if (response > 0) {
//                releaseAdInfo()
//                killProcess()
//            }
        })
    }

    /**
     * 重启需是否广告相关对象数据
     */
    private fun releaseAdInfo() {
        BpApplication.adMobOpenAdManager?.releaseOpenAd()
        AdMobNativeAdManager.release()
        AdMobRewardedAdManager.release()
        AdMobInterstitialAdManager.release()
    }

    override fun onDestroy() {
        super.onDestroy()
        nativeAd?.let { AdMobNativeAdManager.removeUsedNativeAd(it) }
    }

    override fun initImmersionBar() {
        super.initImmersionBar()
        if (languageFrom != null) {
            binding.ivBack.visibility = View.VISIBLE
            binding.ivBack.setOnClickListener { finish() }
        }
        ImmersionBar.with(this).statusBarDarkFont(true).titleBar(binding.toolbar).init()
    }

    override fun initListener() {
        super.initListener()
        binding.tvSave.setOnClickListener(object : DoubleClickListener() {
            override fun onNoDoubleClick(v: View?) {
                changeLanguage(
                    languageList[languageId].language, languageList[languageId].area
                )
            }
        })
        languageTypeAdapter.setLanguageClick(object : BpLanguageTypeAdapter.OnClickListener {
            override fun onLanguageSelected(position: Int) {
                languageId = position
            }
        })
    }

    /**
     * 修改应用内语言设置
     */
    private fun changeLanguage(language: String, area: String) {
        if (language == Constants.dfT && area == Constants.dfC) {
            //如果语言和地区都是空，跟随系统
            SpUtils.saveString(Constants.LOCALE_LANGUAGE, "")
            SpUtils.saveString(Constants.LOCALE_COUNTRY, "")
        } else {
            //不为空，修改app语言，并true是把语言信息保存到sp中，false是不保存到sp中
            val newLocale = Locale(language, area)
            changeAppLanguage(this, newLocale, true)
            changeAppLanguage(BpApplication.context, newLocale, true)
        }
        viewMode.updateLanguage(Constants.USER_ID, languageId)
    }

    //重启app,这一步一定要加上，如果不重启app，可能打开新的页面显示的语言会不正确
    private fun killProcess() {
        val intent: Intent =
            if (firstOpen && AdsSwitch.getBoolean(AdsSwitch.pageLaunchGender)) {
                Intent(BpApplication.context, BpGenderActivity::class.java)
            } else {
                if (languageFrom == null) {
                    Intent(BpApplication.context, BpMainActivity::class.java)
                } else {
                    Intent(BpApplication.context, BpSplashActivity::class.java)
                }
            }
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK)
        BpApplication.context.startActivity(intent)
        Process.killProcess(Process.myPid())
    }

    /**
     * 展示广告
     *     ■ 插页广告资源加载到，立即展示，广告关闭后自动跳转至主页
     *     ■ 插页广告资源未加载到，自动跳转至主页
     */
    private fun loadAdMobInsertAd() {
        if (AdsSwitch.getBoolean(AdsSwitch.adInterLaunchLanguage)) {
            AdMobInterstitialAdManager.setInterstitialAdListener(object :
                AdMobInterstitialAdListener {
                override fun onAdDismissedFullScreenContent() {
                    startBpMainActivity()
                }

                override fun onNotReady() {
                    startBpMainActivity()
                }

                override fun onAdFailedToShowFullScreenContent() {
                    startBpMainActivity()
                }

                override fun onAdShowedFullScreenContent() {
                    //埋点

                }
            })
            AdMobInterstitialAdManager.showInterstitialAd(this)
        } else {
            startBpMainActivity()
        }
    }

    private fun loadTopOnInsertAd() {
        topOnNativeAd?.let { TopOnNativeAdManager.removeUsedNativeAd(it) }
        if (AdsSwitch.getBoolean(AdsSwitch.adInterLaunchLanguage)) {
            if (TopOnInterAdManager.isAdReady()) {
                TopOnInterAdManager.showInterstitialAd(this)
            } else {
                startBpMainActivity()
            }
        } else {
            startBpMainActivity()
        }
    }

    private fun startBpMainActivity() {
        val intent: Intent =
            if (firstOpen && AdsSwitch.getBoolean(AdsSwitch.pageLaunchGender)) {
                Intent(BpApplication.context, BpGenderActivity::class.java)
            } else {
                if (languageFrom == null) {
                    Intent(BpApplication.context, BpMainActivity::class.java)
                } else {
                    Intent(BpApplication.context, BpSplashActivity::class.java)
                }
            }
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK)
        BpApplication.context.startActivity(intent)
        if (languageList[languageId].language != Constants.dfT//默认语言
            || languageList[languageId].area != Constants.dfC
        ) {
            releaseAdInfo()
            Process.killProcess(Process.myPid())
        }
    }
}